from Course_Management_and_Enrollment.course_task_classes import Course
from Progress_Tracking_CLI_DataPersistence.system_modules import ProgressTracker
from Course_Management_and_Enrollment.system_modules import EnrollmentSystem
from Assignment_and_Grading.system_modules import GradingSystem  # 确保从正确的模块导入
from Progress_Tracking_CLI_DataPersistence.data_persistence import DataPersistence
from Progress_Tracking_CLI_DataPersistence.utils import input_validation, error_handling, generate_id, input_choice, input_positive_integer
from Progress_Tracking_CLI_DataPersistence import config
import os
from datetime import datetime, timedelta
import sys
import abc  
from typing import Optional
from typing import Dict, List, Tuple, Optional, Any
from backup_restore_tool import DataBackupRestoreTool  # 新增:数据备份恢复工具
import json

from User_Management.user_classes import User, Student, Teacher, Administrator


class LMS:
    def __init__(self, use_backup=False):
        self.progress_tracker: ProgressTracker = ProgressTracker()  # 进度追踪模块实例
        self.enrollment_system: EnrollmentSystem = EnrollmentSystem()  # 选课系统实例
        self.grading_system: GradingSystem = GradingSystem()  # 成绩管理实例
        
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        
        # 根据use_backup参数选择数据源
        if use_backup:
            # 使用最新的备份文件
            backup_dir = os.path.join(project_root, "backups")
            if os.path.exists(backup_dir):
                # 获取所有备份文件并按修改时间排序
                backup_files = [f for f in os.listdir(backup_dir) if f.endswith('.json')]
                if backup_files:
                    # 按文件名排序(假设文件名包含时间戳)
                    backup_files.sort(reverse=True)
                    data_file_path = os.path.join(backup_dir, backup_files[0])
                    print(f"Using backup file: {data_file_path}")
                else:
                    print("No backup files found. Using default data.json.")
                    data_file_path = os.path.join(project_root, "data.json")
            else:
                print("Backup directory not found. Using default data.json.")
                data_file_path = os.path.join(project_root, "data.json")
        else:
            data_file_path = os.path.join(project_root, "data.json")
        
        self.data_persistence: DataPersistence = DataPersistence(data_file_path)  # 数据持久化实例
        
        # 新增:初始化备份工具
        self.backup_tool = DataBackupRestoreTool(data_file_path)
        
        # 确保User类有_all_users属性
        if not hasattr(User, "_all_users"):
            User._all_users = []
        
        self.current_user: Optional[User] = None  # 当前登录用户
        self.system_status: str = "uninitialized"  # 系统运行状态
        self.last_save_time: Optional[str] = None  # 最后保存时间
        self.last_backup_time: Optional[str] = None  # 最后备份时间
        self.auto_save_interval = 10  # 自动保存间隔(秒) - 10秒
        self.last_auto_save_time = datetime.now() - timedelta(seconds=self.auto_save_interval)  # 上次自动保存时间
        
        # 新增:添加缺失的属性
        self.users = []
        self.courses = []
        self.students = []
        self.teachers = []
        self.data_file = data_file_path

        self._data_changed = False  # 新增:添加数据变更标志位

        self._last_saved_state_hash = None  # 新增:添加最后保存的统计数据哈希值

    def mark_data_changed(self):
        """标记数据已变更"""
        self._data_changed = True
        
    def reset_data_changed(self):
        """重置数据变更标志(保存成功后调用)"""
        self._data_changed = False
        # 计算并存储当前数据状态的哈希值
        self._last_saved_state_hash = self._calculate_data_state_hash()
        
    def _calculate_data_state_hash(self):
        """计算当前数据状态的哈希值用于比较"""
        try:
            # 创建包含关键数据元素的快照
            data_snapshot = {
                'user_count': len(self.users),
                'course_count': len(self.courses),
                'assignment_count': sum(len(t.created_assignments) for t in self.teachers),
            }
            # 使用JSON序列化和哈希函数计算数据指纹
            import hashlib
            data_str = json.dumps(data_snapshot, sort_keys=True)
            return hashlib.md5(data_str.encode()).hexdigest()
        except Exception as e:
            # 改进:记录异常但仍返回一个稳定的哈希值,而不是时间戳
            error_handling(e)
            return "error_state_hash"  
        
    def _encrypt_password(self, raw_password: str) -> str:
        """密码加密方法,与User类中的加密方法完全一致"""
        from User_Management.config import PASSWORD_SALT
        
        # 与User类完全一致的加密逻辑
        combined = raw_password + PASSWORD_SALT
        encrypted = ""
        for char in combined:
            if char.isalpha():
                ascii_offset = ord('a') if char.islower() else ord('A')
                encrypted += chr((ord(char) - ascii_offset + 3) % 26 + ascii_offset)
            else:
                encrypted += char
        return encrypted
        
    def initialize_system(self) -> None:
        """初始化系统:加载数据并设置各模块"""
        try:
            # 1. 先导入所需的类
            from User_Management.user_classes import User, Student, Teacher, Administrator
            from Course_Management_and_Enrollment.course_task_classes import Course
            from Course_Management_and_Enrollment.data_persistence import load_courses as cm_load_courses
            
            # 2. 再加载数据
            data = self.data_persistence.load_data()
            
            # 检查数据是否为空,如果是则初始化默认数据
            if not data.get("users") and not data.get("courses"):
                print("⚠️  No data found. Initializing with default data...")
                self._initialize_default_data()
            else:
                # 关键修改:确保User._all_users已初始化
                if not hasattr(User, "_all_users"):
                    User._all_users = []
                
                # 加载用户数据
                if "users" in data:
                    User.load_all_users(data["users"])
                    print(f"✅ Loaded {len(data['users'])} users")
                    # 更新users, students和teachers属性
                    self.users = User.all_users()
                    self.students = [u for u in self.users if isinstance(u, Student)]
                    self.teachers = [u for u in self.users if isinstance(u, Teacher)]
                
                # 加载课程数据
                # 加载课程数据
                if "courses" in data:
                    # 关键修改:创建一个教师映射字典,用于快速查找
                    teacher_map = {}  
                    for user in User.all_users():
                        if isinstance(user, Teacher):
                            teacher_map[user.teacher_id] = user
                            teacher_map[user.user_id] = user  # 同时映射user_id作为后备
                    
                    # 创建学生映射字典
                    student_map = {}  
                    for user in User.all_users():
                        if isinstance(user, Student):
                            student_map[user.student_id] = user  # 修复:使用user.student_id而不是未定义的student_id
                            student_map[user.user_id] = user
                    
                    # 关键修改:直接在当前作用域实现课程加载逻辑,确保能访问teacher_map
                    Course._all_courses.clear()
                    for course_data in data["courses"]:
                        course_id = course_data.get('course_id')
                        course_name = course_data.get('course_name')
                        course_description = course_data.get('course_description', '')
                        max_students = course_data.get('max_students', 30)
                        status = course_data.get('status', 'pending')
                        
                        # 支持从'teacher_id'和'teacher'两个字段获取教师ID
                        teacher_id = course_data.get('teacher_id', course_data.get('teacher', None))
                        
                        if not all([course_id, course_name]):
                            continue
                        
                        # 查找对应的教师对象 - 使用映射字典提高效率
                        teacher = None
                        if teacher_id and teacher_id in teacher_map:
                            teacher = teacher_map[teacher_id]
                        
                        # 如果找不到教师但有数据,创建一个临时教师对象避免初始化失败
                        if teacher is None and teacher_id:
                            print(f"⚠️  Teacher with ID {teacher_id} not found. Creating temporary teacher.")
                            # 创建一个临时教师对象
                            teacher = Teacher(
                                user_id=f"TEMP_{teacher_id}",
                                username=f"Teacher_{teacher_id}",
                                password="temp123",
                                email=f"temp_{teacher_id}@gt.edu",
                                is_encrypted=True,
                                teacher_id=teacher_id
                            )
                            # 添加到映射中
                            teacher_map[teacher_id] = teacher
                        
                        # 创建课程实例
                        try:
                            course = Course(
                                course_id=course_id,
                                course_name=course_name,
                                teacher=teacher,
                                max_students=max_students,
                                course_description=course_description,
                                status=status
                            )
                        except ValueError as e:
                            print(f"⚠️  Error creating course {course_id}: {e}")
                            # 如果教师缺失,尝试使用第一个可用的教师
                            if "teacher" in str(e).lower() and self.teachers:
                                teacher = self.teachers[0]
                                print(f"🔧  Using fallback teacher: {teacher.username}")
                                course = Course(
                                    course_id=course_id,
                                    course_name=course_name,
                                    teacher=teacher,
                                    max_students=max_students,
                                    course_description=course_description,
                                    status=status
                                )
                    
                    print(f"✅ Loaded {len(data['courses'])} courses")
                    # 关联用户与课程
                    User.associate_users_with_courses()
                    # 更新courses属性
                    self.courses = Course.all_courses()

                if "assignments" in data:
                    from Assignment_and_Grading.course_task_classes import Assignment
                    from User_Management.user_classes import User

                    assignments_map = {}
        
                    # 1. 创建所有作业对象
                    for assignment_data in data["assignments"]:
                        try:
                            # 为作业数据提供默认值,确保即使某些字段缺失也能加载
                            assignment_id = assignment_data.get("assignment_id", generate_id(prefix="ASSIGN_"))
                            title = assignment_data.get("title", "未命名作业")
                            content = assignment_data.get("content", "")
                            due_date_str = assignment_data.get("due_date", datetime.now().isoformat())
                            course_id = assignment_data.get("course_id")
                            
                            # 为必填字段提供默认值
                            required_format = assignment_data.get("required_format", "text")
                            total_points = assignment_data.get("total_points", 100)
                            
                            # 查找对应的课程对象
                            course = None
                            if course_id:
                                for c in self.courses:
                                    if c.course_id == course_id:
                                        course = c
                                        break
                            
                            # 如果找不到课程,跳过此作业
                            if not course:
                                print(f"⚠️  跳过作业 {title} ({assignment_id}): 无法找到课程ID: {course_id}")
                                continue
                                
                            # 创建作业对象
                            assignment = Assignment(
                                assignment_id=assignment_id,
                                assignment_title=title,
                                assignment_content=content,
                                due_date_str=due_date_str,
                                course=course,
                                required_format=required_format,
                                total_points=total_points
                            )
                            assignments_map[assignment.assignable_id] = assignment
                            
                            # 加载提交信息
                            if "submissions" in assignment_data:
                                for student_id, submission_data in assignment_data["submissions"].items():
                                    try:
                                        submit_time = datetime.fromisoformat(submission_data.get("submit_time", datetime.now().isoformat()))
                                        is_late = submission_data.get("is_late", False)
                                        score = submission_data.get("score", None)
                                        content = submission_data.get("content", "")
                                        
                                        if not hasattr(assignment, "submissions"):
                                            assignment.submissions = {}

                                        if student_id not in assignment.submissions:
                                            assignment.submissions[student_id] = {
                                                "content": content,
                                                "submit_time": submit_time,
                                                "is_late": is_late,
                                                "status": "submitted",
                                                "score": score,
                                                "grade_time": None,
                                                "graded_by": None,
                                                "comment": ""
                                            }
                                        else:
                                            assignment.submissions[student_id]["submit_time"] = submit_time
                                            assignment.submissions[student_id]["is_late"] = is_late
                                            if score is not None:
                                                assignment.submissions[student_id]["score"] = score
                                    except Exception as submit_e:
                                        print(f"⚠️  加载提交信息失败 for {student_id}: {submit_e}")

                        except Exception as e:
                            print(f"⚠️  创建作业对象失败: {str(e)}")
                            continue
        
                    # 2. 关联作业到教师和课程
                    # 为教师关联created_assignments
                    for user in User.all_users():
                        if hasattr(user, 'created_assignments') and hasattr(user, 'to_dict'):
                            user_dict = user.to_dict()
                            if "created_assignments" in user_dict:
                                user.created_assignments = []
                                for assign_id in user_dict["created_assignments"]:
                                    if assign_id in assignments_map:
                                        user.created_assignments.append(assignments_map[assign_id])
        
                    # 为课程关联course_assignments
                    course_data_map = {}
                    if "courses" in data:
                        for course_data in data["courses"]:
                            if "course_id" in course_data:
                                course_data_map[course_data["course_id"]] = course_data

                    for course in self.courses:
                        if hasattr(course, 'course_assignments'):
                            course.course_assignments = []
                            if course.course_id in course_data_map:
                                course_data_for_course = course_data_map[course.course_id]
                                if "course_assignments" in course_data_for_course:
                                    for assign_id in course_data_for_course.get("course_assignments", []):
                                        if assign_id in assignments_map:
                                            course.course_assignments.append(assignments_map[assign_id])

                    print(f"✅ Loaded {len(assignments_map)} assignments")
                
            
            print("✅ System initialized successfully!")
            
        except Exception as e:
            error_handling(e)
            print("⚠️  System initialization failed. Please check the system logs for more details.")

    def _initialize_sample_grades(self) -> None:
        """初始化样本成绩数据"""
        try:
            # 获取一些学生和课程示例
            students = []
            courses = []
            
            if hasattr(User, "all_users"):
                for user in User.all_users():
                    if isinstance(user, Student) and user.enrolled_courses:
                        students.append(user)
                        # 获取学生的课程
                        for course in user.enrolled_courses:
                            if course not in courses:
                                courses.append(course)
            
            # 为每个学生的每门课程添加一些测试成绩
            for student in students:
                for course in student.enrolled_courses:
                    # 创建一些任务ID和分数
                    tasks = {
                        "HW1": 85 + (hash(student.username) % 15),
                        "Quiz1": 80 + (hash(course.course_id) % 20),
                        "Midterm": 82 + ((hash(student.username) + hash(course.course_id)) % 18)
                    }
                    
                    # 记录成绩
                    for task_id, score in tasks.items():
                        self.grading_system.record_grade(
                            student_id=student.student_id,
                            course_id=course.course_id,
                            task_id=task_id,
                            score=score
                        )
            
            print(f"✅ Initialized sample grades for {len(students)} students in {len(courses)} courses")
            
        except Exception as e:
            error_handling(e)
            print("⚠️  Failed to initialize sample grades.")


    def _sync_grades_to_students(self) -> None:
        """将成绩数据同步到学生对象"""
        try:
            # 获取所有学生
            if not hasattr(User, "all_users"):
                return
                
            for user in User.all_users():
                if isinstance(user, Student):
                    student_id = user.student_id
                    # 初始化学生的grades字典(如果不存在)
                    if not hasattr(user, 'grades'):
                        user.grades = {}
                    
                    # 直接从grading_system获取成绩数据
                    grade_data = self.grading_system.grade_records
                    
                    # 获取学生已注册的课程
                    enrolled_course_ids = {course.course_id: course for course in user.enrolled_courses}
                    
                    for course_id, students_data in grade_data.items():
                        # 检查该学生是否有这门课的成绩
                        if student_id in students_data:
                            # 找到对应的课程对象
                            if course_id in enrolled_course_ids:
                                course = enrolled_course_ids[course_id]
                                # 计算该课程的平均成绩作为final_grade
                                task_scores = students_data[student_id].values()
                                if task_scores:
                                    final_grade = sum(task_scores) / len(task_scores)
                                    user.grades[course] = final_grade
                            else:
                                # 如果在已选课程中找不到,也添加成绩但标记为未注册
                                # 创建一个具有基本信息的课程对象
                                from Course_Management_and_Enrollment.course_task_classes import Course
                                dummy_teacher = None
                                for user in User.all_users():
                                    if isinstance(user, Teacher):
                                        dummy_teacher = user
                                        break

                                dummy_course = Course(
                                    course_id=course_id,
                                    course_name=f"Course {course_id}",
                                    course_description="This course was not found in your enrollment list",
                                    teacher=dummy_teacher
                                )
                                # 计算成绩
                                task_scores = students_data[student_id].values()
                                if task_scores:
                                    final_grade = sum(task_scores) / len(task_scores)
                                    user.grades[dummy_course] = final_grade
        except Exception as e:
            error_handling(e)
            print("⚠️  Failed to sync grades to students.")


    def _initialize_default_data(self) -> None:
        """初始化默认数据"""
        try:
            # 创建一些默认用户(使用正确的密码加密)
            default_users = [
                {
                    "user_id": "USER_1",
                    "username": "admin",
                    "password": self._encrypt_password("admin123"),
                    "email": "admin@gt.edu",
                    "role": "admin"
                },
                {
                    "user_id": "USER_2", 
                    "username": "john_smith",
                    "password": self._encrypt_password("SmithPass123"),
                    "email": "john.smith@gt.edu",
                    "role": "student"
                },
                {
                    "user_id": "USER_3",
                    "username": "prof_wang", 
                    "password": self._encrypt_password("WangPass456"),
                    "email": "wang.prof@gt.edu",
                    "role": "teacher"
                }
            ]
            
            # 保存默认数据
            data = {
                "users": default_users,
                "courses": [],
                "progress": {},
                "grades": {}
            }
            
            self.data_persistence.save_data(data)
            User.load_all_users(default_users)
            
            print("✅ Default data initialized successfully!")
            
        except Exception as e:
            error_handling(e)
            print("⚠️  Default data initialization failed.")  

    def run_cli(self) -> None:
        """运行CLI界面"""
        self.initialize_system()
        
        while True:
            # 新增:检查自动保存
            self.check_auto_save()
            
            if not self.current_user:
                self._show_login_menu()
            else:
                if self.current_user.role == "admin":
                    self._show_admin_menu()
                elif self.current_user.role == "teacher":
                    self._show_teacher_menu()
                elif self.current_user.role == "student":
                    self._show_student_menu()
                else:
                    print("❌ Invalid user role. Logging out...")
                    self.current_user = None

    def save_data(self, force=False):
        """保存所有数据到文件,仅在有更改时或强制时保存"""
        try:
            # 检查数据是否有变化
            data_has_changed = force or self._data_changed  
            
            current_hash = self._calculate_data_state_hash()
            if not force and self._last_saved_state_hash and current_hash == self._last_saved_state_hash:
                data_has_changed = False
            
            # 强制保存即使认为数据没有变化,确保删除操作被保存
            if force or data_has_changed:
                print("开始保存数据...")
                # 确保users列表包含所有用户,并去重
                all_users = User.all_users()
                # 去重处理:使用user_id作为唯一标识
                unique_users_dict = {user.user_id: user for user in all_users}
                self.users = list(unique_users_dict.values())
                self.students = [u for u in self.users if isinstance(u, Student)]
                self.teachers = [u for u in self.users if isinstance(u, Teacher)]
                
                # 同时更新User._all_users,避免未来重复
                if len(unique_users_dict) < len(all_users):
                    print(f"⚠️  发现并移除了 {len(all_users) - len(unique_users_dict)} 个重复用户")
                    User._all_users = self.users

                for user in self.users:
                    if user.role == "student":
                        # 确保学生的grades字典被正确填充
                        # 获取GradingSystem实例计算所有课程的最新成绩
                        from Assignment_and_Grading.system_modules import GradingSystem
                        grading_system = GradingSystem(self)

                        # 为每个已注册课程更新成绩
                        updated_grades = {}
                        for course in user.enrolled_courses:
                            # 计算最新成绩
                            course_score = grading_system.calculate_total_score(user.student_id, course)
                            updated_grades[course] = course_score
        
                        # 更新学生的grades字典
                        user.grades = updated_grades

                # 序列化用户数据
                serialized_users = []
                for user in self.users:
                    try:
                        user_data = user.to_dict()
                        # 根据用户角色添加特定字段
                        if user.role == "student":
                            user_data["student_id"] = user.student_id
                            user_data["enrolled_courses"] = [course.course_id for course in user.enrolled_courses]
                            # 确保成绩数据被正确序列化
                            grades_dict = {}
                            for course, score in user.grades.items():
                                # 使用course_id作为键,确保正确序列化
                                grades_dict[course.course_id] = score
                            user_data["grades"] = grades_dict
                            
                            # 序列化已提交的作业
                            submitted_assignments_data = []
                            for submission in user.submitted_assignments:
                                submission_data = submission.copy()
                                # 如果提交记录中包含course对象,转换为course_id
                                if "course" in submission_data and submission_data["course"]:
                                    submission_data["course_id"] = submission_data["course"].course_id  
                                    del submission_data["course"]
                                submitted_assignments_data.append(submission_data)
                            user_data["submitted_assignments"] = submitted_assignments_data
                        elif user.role == "teacher":
                            user_data["teacher_id"] = user.teacher_id
                            user_data["managed_courses"] = [course.course_id for course in user.managed_courses]
                            user_data["created_assignments"] = [assign.assignable_id for assign in user.created_assignments]
                        elif user.role == "admin":
                            user_data["admin_id"] = user.admin_id
                        serialized_users.append(user_data)
                    except Exception as e:
                        print(f"序列化用户 {user.username} 时出错: {str(e)}")
                
                # 序列化课程数据
                # 从所有教师的managed_courses中收集课程数据
                # 使用集合避免重复课程
                all_courses_set = set()
                
                # 首先添加self.courses中的课程
                for course in self.courses:
                    all_courses_set.add(course)
                
                # 然后添加所有教师managed_courses中的课程
                for user in self.users:
                    if user.role == "teacher":
                        for course in user.managed_courses:
                            all_courses_set.add(course)
                
                # 转换为列表并序列化
                serialized_courses = []
                for course in all_courses_set:
                    try:
                        course_data = {
                            "course_id": course.course_id,
                            "course_name": course.course_name,
                            "course_description": course.course_description,
                            "teacher_id": course.teacher.teacher_id if course.teacher else None,
                            "max_students": course.max_students,
                            "enrolled_students": [student.student_id for student in course.enrolled_students],
                            "course_assignments": [assign.assignable_id for assign in course.course_assignments],
                            "status": course.status
                        }
                        serialized_courses.append(course_data)
                    except Exception as e:
                        print(f"序列化课程 {course.course_name} 时出错: {str(e)}")
                
                serialized_assignments = []
                all_assignments = {}
            
                # 从教师的created_assignments中收集作业
                for user in self.users:
                    if user.role == "teacher":
                        for assignment in user.created_assignments:
                            if assignment.assignable_id not in all_assignments:
                                serialized = assignment.to_dict()
                                serialized_assignments.append(serialized)
                                all_assignments[assignment.assignable_id] = serialized

                # 同时从学生的submitted_assignments中收集作业,确保不遗漏
                for user in self.users:
                    if user.role == "student":
                        for submission in user.submitted_assignments:
                            if not submission or not isinstance(submission, dict):
                                continue
                            
                            assignment_id = submission.get("assignment_id")
                            if assignment_id and assignment_id not in all_assignments:
                                # 尝试找到对应的作业对象
                                found = False
                                for teacher in self.teachers:
                                    for assignment in teacher.created_assignments:
                                        if assignment.assignment_id == assignment_id:
                                            serialized = assignment.to_dict()
                                            serialized_assignments.append(serialized)
                                            all_assignments[assignment_id] = serialized
                                            found = True
                                            break
                                # 如果找不到,创建一个基本的作业记录
                                if not found:
                                    submit_time = submission.get("submit_time")
                                    due_date = submit_time.isoformat() if isinstance(submit_time, datetime) else datetime.now().isoformat()
                                    basic_assignment = {
                                        "assignment_id": assignment_id,
                                        "title": f" {assignment_id}",
                                        "content": "",
                                        "due_date": due_date,
                                        "course_id": submission.get("course_id"),
                                        "submissions": {
                                            user.student_id: submission
                                        }
                                    }
                                    serialized_assignments.append(basic_assignment)
                                    all_assignments[assignment_id] = basic_assignment
          
                # 组合所有数据
                all_data = {
                    "metadata": {
                        "version": "1.0",
                        "last_update": datetime.now().isoformat(),
                        "total_users": len(serialized_users),
                        "total_courses": len(serialized_courses),
                    },
                    "users": serialized_users,
                    "courses": serialized_courses,
                    "assignments": serialized_assignments
                }
                
                # 保存数据
                self.data_persistence.save_data(all_data)
                self.last_save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                print(f"✅ 数据保存成功 (时间: {self.last_save_time})")
                
                # 重置数据变更标志
                self.reset_data_changed()
                return True
            else:
                print("数据未发生变化,跳过保存操作")
                return True
        except Exception as e:
            print(f"❌ 保存数据时出错: {str(e)}")
            error_handling(e)
            return False
        
    def validate_data(self, data):
        """验证数据的完整性和有效性"""
        try:
            # 检查必要字段是否存在
            required_keys = ['users', 'courses', 'progress', 'grades']
            for key in required_keys:
                if key not in data:
                    print(f"❌ Missing required data field: {key}")
                    return False
        
            # 验证用户数据
            for user in data['users']:
                if not all(k in user for k in ['user_id', 'username', 'password', 'email', 'role']):
                    print(f"❌ Incomplete user data: {user.get('username', 'unknown')}")
                    return False
        
            # 验证课程数据
            for course in data['courses']:
                if not all(k in course for k in ['course_id', 'course_name', 'teacher_id']):
                    print(f"❌ Incomplete course data: {course.get('course_name', 'unknown')}")
                    return False
        
            return True
        except Exception as e:
            print(f"❌ Data validation error: {str(e)}")
            return False

    # 新增:在重要操作前创建备份的方法
    def create_backup_before_operation(self, operation_name):
        """在执行重要操作前创建备份,避免冗余备份"""
        try:
            # 检查是否真的有数据变化需要备份
            if self.data_has_changed():
                backup_path = self.backup_tool.create_backup(f"before_{operation_name}")
                if backup_path:
                    self.last_backup_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    print(f"✅ Backup created before {operation_name} operation")
                else:
                    print(f"⚠️  Failed to create backup before {operation_name}: {str(e)}")
        except Exception as e:
            print(f"⚠️  Failed to create backup before {operation_name}: {str(e)}")

    def data_has_changed(self):
        """检测数据是否发生变化"""
        try:
            if self._data_changed:
                return True
            
            current_hash = self._calculate_data_state_hash()
            hash_changed = not self._last_saved_state_hash or current_hash != self._last_saved_state_hash

            return hash_changed
        except:
            return True


    # 新增:定期自动保存检查
    # 修改自动保存检查方法
    def check_auto_save(self):
        """检查是否需要自动保存"""
        try:
            # 检查是否达到自动保存间隔
            current_time = datetime.now()
            time_since_last_save = (current_time - self.last_auto_save_time).total_seconds()
            
            # 使用60秒的自动保存间隔,与GUI中的设置保持一致
            if self.data_has_changed() and time_since_last_save >= 60:
                # 保存前再次检查数据是否确实有变化
                if self._data_changed or self._calculate_data_state_hash() != self._last_saved_state_hash:
                    self.save_data(force=False)
                    self.last_auto_save_time = current_time
        except Exception as e:
            error_handling(e)
            print(f"⚠️  Auto-save check failed: {str(e)}")

    def save_user_incrementally(self, user) -> None:
        """增量保存用户数据"""
        try:
            user_data = {
                "user_id": user.user_id,
                "username": user.username,
                "password": user._password,
                "email": user.email,
                "role": user.role
            }
            
            # 根据用户角色添加特定字段
            if isinstance(user, Student):
                user_data.update({
                    "student_id": user.student_id,
                    "is_active": user.is_active,
                    # 注意:复杂对象如enrolled_courses不直接保存,通过其他机制关联
                })
            elif isinstance(user, Teacher):
                user_data.update({
                    "teacher_id": user.teacher_id,
                    # 注意:复杂对象如managed_courses不直接保存,通过其他机制关联
                })
        
            # 调用增量保存方法
            self.data_persistence.add_user(user_data)
        except Exception as e:
            print(f"⚠️  Incremental user saving failed: {str(e)}")

    def save_course_incrementally(self, course):
        """增量保存课程数据"""
        try:
            # 先创建备份
            self.create_backup_before_operation("course_modification")
            
            # 加载现有数据
            existing_data = self.data_persistence.load_data()
            
            # 准备课程数据
            course_data = {
                "course_id": course.course_id,
                "course_name": course.course_name,
                "course_description": course.course_description,
                "teacher": course.teacher.teacher_id if course.teacher else None
            }
            
            # 检查课程是否已存在
            course_exists = False
            for i, c in enumerate(existing_data["courses"]):
                if c["course_id"] == course.course_id:
                    existing_data["courses"][i] = course_data
                    course_exists = True
                    print(f"✅ Course {course.course_id} updated")
                    break
            
            if not course_exists:
                existing_data["courses"].append(course_data)
                print(f"✅ Course {course.course_id} added")
            
            # 保存更新后的数据
            self.data_persistence.save_data(existing_data)
            self.last_save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        except Exception as e:
            error_handling(e)
            print("⚠️  Failed to save course incrementally.")

    def save_progress_incrementally(self, student_id, course_id, progress_data):
        """增量保存学生进度数据"""
        try:
            # 加载现有数据
            existing_data = self.data_persistence.load_data()
            
            # 确保progress字段存在
            if "progress" not in existing_data:
                existing_data["progress"] = {}
            
            # 构建键并更新进度数据
            progress_key = f"{student_id}_{course_id}"
            existing_data["progress"][progress_key] = progress_data
            
            # 保存更新后的数据
            self.data_persistence.save_data(existing_data)
            self.last_save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"✅ Progress data saved for student {student_id} in course {course_id}")
        except Exception as e:
            error_handling(e)
            print("⚠️  Failed to save progress incrementally.")

    def save_grades_incrementally(self):
        """增量保存成绩数据"""
        try:
            # 先创建备份
            self.create_backup_before_operation("grading")
            
            # 加载现有数据
            existing_data = self.data_persistence.load_data()
            
            # 更新成绩数据
            existing_data["grades"] = self.grading_system.grade_records
            
            # 保存更新后的数据
            self.data_persistence.save_data(existing_data)
            self.last_save_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print("✅ Grade data saved successfully")
        except Exception as e:
            error_handling(e)
            print("⚠️  Failed to save grades incrementally.")



    def update_user_incrementally(self, user_id: str, updated_data: Dict[str, Any]) -> None:
        """增量更新用户数据"""
        try:
            self.data_persistence.update_user(user_id, updated_data)
        except Exception as e:
            error_handling(e)
            print("⚠️  Incremental user update failed. Please check the system logs for more details.")

    def update_progress_incrementally(self, user_id: str, course_id: str, progress_data: Dict[str, Any]) -> None:
        """增量更新进度数据"""
        try:
            self.data_persistence.update_progress(user_id, course_id, progress_data)
        except Exception as e:
            error_handling(e)
            print("⚠️  Incremental progress update failed. Please check the system logs for more details.")

    def update_grade_incrementally(self, user_id: str, course_id: str, grade_data: Dict[str, Any]) -> None:
        """增量更新成绩数据"""
        try:
            self.data_persistence.update_grade(user_id, course_id, grade_data)
        except Exception as e:
            error_handling(e)
            print("⚠️  Incremental grade update failed. Please check the system logs for more details.")

    # ------------------------------ CLI菜单私有方法(封装菜单逻辑) ------------------------------
    def _show_login_menu(self) -> None:
        print("\n" + "="*50)
        print(f"=== {config.SYSTEM_NAME} v{config.SYSTEM_VERSION} Login Menu ===")
        print("="*50)
        print("1. Login")
        print("2. Register")
        print("3. Exit")
        print("="*50)

        try:
            choice = input("Enter your choice (1-3): ").strip()

            if choice == "1":
                self._handle_login()
            elif choice == "2":
                self._handle_register()
            elif choice == "3":
                print("Thank you for using the system. Goodbye!")
                sys.exit(0)
            else:
                print("⚠️  Invalid choice. Please select a valid option.")
        except Exception as e:
            error_handling(e)
            print("⚠️  Login menu operation failed. Please check the system logs for more details.")

    def _handle_login(self):
        """处理用户登录"""
        username = input("Enter username: ").strip()
        password = input("Enter password: ").strip()
        
        try:
            # 遍历所有用户,尝试登录
            if hasattr(User, "all_users"):
                for user in User.all_users():
                    if user.login(username, password):
                        self.current_user = user
                        print("✅ Login successful!")
                        
                        # 为管理员初始化用户和课程列表
                        if isinstance(user, Administrator):
                            user.system_users = User.all_users()
                            if hasattr(Course, "all_courses"):
                                user.all_courses = Course.all_courses()
                        
                        return
            
            # 如果没有找到匹配的用户
            print("❌ Invalid username or password!")
            
        except Exception as e:
            error_handling(e)
            print("⚠️  Login operation failed. Please check the system logs for more details.")

    def _handle_register(self):
        """处理用户注册"""
        print("\n" + "="*50)
        print("=== User Registration ===")
        print("="*50)
    
        try:
            # 获取用户信息
            username = input("Enter username: ").strip()
            password = input("Enter password: ").strip()
            email = input("Enter email: ").strip()
        
            # 选择用户角色
            print("\nSelect user role:")
            print("1. Student")
            print("2. Teacher")
            print("3. Administrator")
            role_choice = input("Enter role (1-3): ").strip()
            
            role_mapping = {"1": "student", "2": "teacher", "3": "admin"}
            if role_choice not in role_mapping:
                print("❌ Invalid role selection!")
                return
            
            role = role_mapping[role_choice]
        
            # 直接调用User类的register方法
            new_user = User.register(username, password, email, role)
            
            if new_user:
                print(f"✅ User '{username}' registered successfully!")
                print(f"📝 User ID: {new_user.user_id}")
                print(f"🎯 Role: {role}")
                self.save_user_incrementally(new_user)
            else:
                print("❌ Failed to register user!")
            
        except Exception as e:
            error_handling(e)
            print("⚠️  Registration operation failed. Please check the system logs for more details.")

    def _show_student_menu(self) -> None:
        print("\n" + "="*50)
        print(f"=== {config.SYSTEM_NAME} v{config.SYSTEM_VERSION} Student Menu ===")
        print("="*50)
        print("1. View Dashboard")
        print("2. View Progress Report")
        print("3. View Grades")
        print("4. Update Profile")
        print("5. Enroll in Course")  # 添加选课选项
        print("6. Drop Course")      # 添加退课选项
        print("7. Logout")
        print("="*50)
    
        try:
            choice = input("Enter your choice (1-7): " ).strip()
            if choice == "1":
                self.current_user.view_dashboard()
            elif choice == "2":        
                progress_report = self.progress_tracker.generate_progress_report(self.current_user)
                print(progress_report)
            elif choice == "3":
                grade_report = self.grading_system.generate_grade_report(self.current_user)
                print(grade_report)
            elif choice == "4":
                new_info = {}
                new_email = input("Enter new email (or press Enter to skip): ")
                if new_email:
                    new_info["email"] = new_email
                new_username = input("Enter new username (or press Enter to skip): ")
                if new_username:
                    new_info["username"] = new_username
                if new_info:
                    self.current_user.update_profile(new_info)
                    self.update_user_incrementally(self.current_user.user_id, new_info)  # 增量更新用户
            elif choice == "5":
                self._handle_enroll_course()
            elif choice == "6":
                self._handle_drop_course()
            elif choice == "7":
                self.save_data()  # 添加数据保存
                self.current_user.logout()
                self.current_user = None
            else:
                print("⚠️  Invalid choice. Please select a valid option.")
        except Exception as e:
            error_handling(e)
            print("⚠️  Student menu operation failed. Please check the system logs for more details.")

    def _show_teacher_menu(self) -> None:
        print("\n" + "="*50)
        print(f"=== {config.SYSTEM_NAME} v{config.SYSTEM_VERSION} Teacher Menu ===")
        print("="*50)
        print("1. View Dashboard")
        print("2. Create Course")
        print("3. View Class Roster")
        print("4. Grade Assignment")
        print("5. Logout")
        print("="*50)
        
        try:
            choice = input("Enter your choice (1-5): ").strip()
            if choice == "1":
                self.current_user.view_dashboard()
            elif choice == "2":
                self._handle_create_course()
            elif choice == "3":
                self._handle_view_class_roster()
            elif choice == "4":
                self._handle_grade_assignment()
            elif choice == "5":
                self.current_user.logout()
                self.current_user = None
            else:
                print("⚠️  Invalid choice. Please select a valid option.")
        except Exception as e:
            error_handling(e)
            print("⚠️  Teacher menu operation failed. Please check the system logs for more details.")
    
    def _show_admin_menu(self) -> None:
        print("\n" + "="*50)
        print(f"=== {config.SYSTEM_NAME} v{config.SYSTEM_VERSION} Admin Menu ===")
        print("="*50)
        print("1. View Dashboard")
        print("2. Add User")
        print("3. View System Stats")
        print("4. Approve Course")
        print("5. Logout")
        print("="*50)
        
        try:
            choice = input("Enter your choice (1-5): ").strip()
            if choice == "1":
                self.current_user.view_dashboard()
            elif choice == "2":
                self._handle_add_user()
            elif choice == "3":
                if hasattr(self.current_user, "view_system_stats"):
                    self.current_user.view_system_stats()
                else:
                    print("⚠️ Error: Current user does not have view_system_stats method.")
            elif choice == "4":
                self._handle_approve_course()
            elif choice == "5":
                self.current_user.logout()
                self.current_user = None
            else:
                print("⚠️  Invalid choice. Please select a valid option.")
        except Exception as e:
            error_handling(e)
            print("⚠️  Admin menu operation failed. Please check the system logs for more details.")

    def _handle_add_user(self):
        """处理添加用户的功能,显示用户类型选择菜单"""
        print("\n=== Add User ===")
        print("Select user type to add:")
        print("1. Student")
        print("2. Teacher")
        print("3. Administrator")
        print("4. Back to Admin Menu")
        
        try:
            choice = input("Enter your choice (1-4): " ).strip()
            if choice == "1":
                self._add_student()
            elif choice == "2":
                self._add_teacher()
            elif choice == "3":
                self._add_administrator()
            elif choice == "4":
                return  # 返回管理员菜单
            else:
                print("⚠️  Invalid choice. Please select a valid option.")
        except Exception as e:
            error_handling(e)
            print("⚠️  Failed to add user. Please try again.")


    def _add_student(self):
        """添加学生用户"""
        print("\n=== Add Student ===")
        username = input("Enter username: ").strip()
        password = input("Enter password: ").strip()
        email = input("Enter email: ").strip()
        
        if not all([username, password, email]):
            print("❌ All fields are required!")
            return
        
        try:
            # 创建Student对象,然后调用Administrator的add_user方法
            from User_Management.utils import generate_id
            user_id = generate_id("USER")
            student = Student(user_id, username, password, email, role="student")
            result = self.current_user.add_user(student)
            
            if result:
                print("✅ Student added successfully!")
                self.save_user_incrementally(student)  # 增量保存用户
            else:
                print("❌ Failed to add student!")
                
        except Exception as e:
            error_handling(e)
            print("❌ Failed to add student!")

    def _add_teacher(self):
        """添加教师用户"""
        print("\n=== Add Teacher ===")
        username = input("Enter username: ").strip()
        password = input("Enter password: ").strip()
        email = input("Enter email: ").strip()
        
        if not all([username, password, email]):
            print("❌ All fields are required!")
            return
        
        try:
            # 创建Teacher对象,然后调用Administrator的add_user方法
            from User_Management.utils import generate_id
            user_id = generate_id("USER")
            teacher = Teacher(user_id, username, password, email)
            result = self.current_user.add_user(teacher)
            
            if result:
                print("✅ Teacher added successfully!")
                self.save_user_incrementally(teacher)  # 增量保存用户
            else:
                print("❌ Failed to add teacher!")
                
        except Exception as e:
            error_handling(e)
            print("❌ Failed to add teacher!")

    def _add_administrator(self):
        """添加管理员用户"""
        print("\n=== Add Administrator ===")
        username = input("Enter username: ").strip()
        password = input("Enter password: ").strip()
        email = input("Enter email: ").strip()
        
        if not all([username, password, email]):
            print("❌ All fields are required!")
            return
        
        try:
            # 创建Administrator对象,然后调用Administrator的add_user方法
            from User_Management.utils import generate_id
            user_id = generate_id("USER")
            admin = Administrator(user_id, username, password, email)
            result = self.current_user.add_user(admin)
            
            if result:
                print("✅ Administrator added successfully!")
            else:
                print("❌ Failed to add administrator!")
                
        except Exception as e:
            error_handling(e)
            print("❌ Failed to add administrator!")

    def _handle_enroll_course(self) -> None:
        """处理学生选课"""
        self.create_backup_before_operation("course_enrollment")
        """处理学生选课"""
        try:
            # 获取所有已批准的课程
            available_courses = [course for course in Course.all_courses() if course.status == "approved"]
        
            if not available_courses:
                print("\n⚠️  Currently, there are no available courses to enroll.")
                return
        
            # 显示可选课程列表
            print("\n=== Available Courses ===")
            for i, course in enumerate(available_courses, 1):
                print(f"{i}. Course ID: {course.course_id} | Course Name: {course.course_name} | Teacher: {course.teacher.username} | Capacity: {course.current_enrollment}/{course.max_students}")
        
            # 选择要选的课程
            choice = input_choice("Enter the number of the course you want to enroll: ", len(available_courses))
            if choice is None:
                return
        
            selected_course = available_courses[choice - 1]
        
            # 调用学生的选课方法
            if isinstance(self.current_user, Student):
                success = self.current_user.enroll_course(selected_course)
            
                if success:
                    print(f"\n✅ Successfully enrolled in course '{selected_course.course_name}'!")
                    # 保存更新后的用户数据
                    self.save_user_incrementally(self.current_user)
                    # 保存更新后的课程数据
                    self.save_course_incrementally(selected_course)
                else:
                    print("\n❌ Failed to enroll in course. Possible reasons: course is full or you have already enrolled in this course.")
        except Exception as e:
            error_handling(e)
            print("⚠️ Failed to enroll in course. Please try again later.")

    # 在LMS类中添加处理退课申请的方法
    def _handle_drop_course_requests(self) -> None:
        """处理学生退课申请(管理员功能)"""
        try:
            # 注意:这里只是示例,实际应用中应该有存储退课申请的数据结构
            print("\n=== Pending Drop Course Requests ===")
            print("Current system does not support drop course requests storage.")
        
            # 实际应用中,这里应该显示所有待审批的退课申请列表
            # 并提供审批选项
        except Exception as e:
            error_handling(e)
            print("⚠️ Failed to handle drop course requests. Please try again later.")

    def _handle_view_assignment_submission(self):
        """处理查看学生作业提交内容"""
        if not isinstance(self.current_user, Teacher):
            print("❌ Only teachers can view assignment submissions.")
            return
            
        try:
            # 显示教师管理的课程
            managed_courses = self.current_user.managed_courses
            if not managed_courses:
                print("⚠️  You are not managing any courses.")
                return
                
            print("\nYour managed courses:")
            for i, course in enumerate(managed_courses, 1):
                print(f"{i}. {course.course_name} (ID: {course.course_id})")
                
            # 选择课程
            choice = input("Select a course (1-{}): ".format(len(managed_courses))).strip()
            try:
                course_index = int(choice) - 1
                if course_index < 0 or course_index >= len(managed_courses):
                    print("❌ Invalid course selection.")
                    return
                selected_course = managed_courses[course_index]
            except ValueError:
                print("❌ Invalid input. Please enter a number.")
                return
                
            # 显示课程中的作业
            if hasattr(selected_course, 'course_assignments') and selected_course.course_assignments:
                print("\nAssignments in this course:")
                for i, assignment in enumerate(selected_course.course_assignments, 1):
                    print(f"{i}. {assignment.title} (Due: {assignment.due_date})")
                    
                # 选择作业
                assignment_choice = input("Select an assignment (1-{}): ".format(
                    len(selected_course.course_assignments))).strip()
                try:
                    assignment_index = int(assignment_choice) - 1
                    if assignment_index < 0 or assignment_index >= len(selected_course.course_assignments):
                        print("❌ Invalid assignment selection.")
                        return
                    selected_assignment = selected_course.course_assignments[assignment_index]
                except ValueError:
                    print("❌ Invalid input. Please enter a number.")
                    return
            else:
                print("⚠️  No assignments found for this course.")
                return
                
            # 显示提交该作业的学生
            if hasattr(selected_assignment, 'submissions') and selected_assignment.submissions:
                print("\nStudents who submitted this assignment:")
                for i, (student_id, submission) in enumerate(selected_assignment.submissions.items(), 1):
                    # 查找学生对象获取姓名
                    student_name = "Unknown"
                    for user in User.all_users():
                        if isinstance(user, Student) and getattr(user, 'student_id', None) == student_id:
                            student_name = user.username
                            break
                    status = "Graded" if submission.get('score') is not None else "Not Graded"
                    print(f"{i}. {student_name} (ID: {student_id}) - {status}")
                    
                # 选择学生
                student_choice = input("Select a student to view submission (1-{}): ".format(
                    len(selected_assignment.submissions))).strip()
                try:
                    student_index = int(student_choice) - 1
                    if student_index < 0 or student_index >= len(selected_assignment.submissions):
                        print("❌ Invalid student selection.")
                        return
                    student_id = list(selected_assignment.submissions.keys())[student_index]
                    
                    # 查找学生对象
                    selected_student = None
                    for user in User.all_users():
                        if isinstance(user, Student) and getattr(user, 'student_id', None) == student_id:
                            selected_student = user
                            break
                            
                    if selected_student:
                        # 调用Teacher的view_student_assignment方法
                        success, result = self.current_user.view_student_assignment(selected_assignment, selected_student)
                        if success:
                            print("\n" + "="*50)
                            print(f"作业: {result['assignment_title']}")
                            print(f"学生: {result['student_name']} (ID: {student_id})")
                            print(f"提交时间: {result['submit_time']}")
                            print(f"是否迟交: {'是' if result['is_late'] else '否'}")
                            print(f"分数: {result['score'] if result['score'] is not None else '未评分'}")
                            print("="*50)
                            print("作业内容:")
                            print("="*50)
                            print(result['content'])
                            print("="*50)
                        else:
                            print(f"❌ {result}")
                    else:
                        print("❌ Student not found.")
                except ValueError:
                    print("❌ Invalid input. Please enter a number.")
                    return
            else:
                print("⚠️  No submissions found for this assignment.")
        except Exception as e:
            print(f"⚠️  Failed to view assignment submission: {e}")
    
    def _handle_drop_course(self):
        """处理学生退课功能"""
        self.create_backup_before_operation("course_drop")
        """处理学生退课功能"""
        print("\n" + "="*50)
        print("=== Drop Course ===")
        print("="*50)
        
        try:
            # 检查学生是否有已选课程
            if not self.current_user.enrolled_courses:
                print("❌ You are not enrolled in any courses.")
                return
            
            # 显示学生已选课程列表
            print("Your enrolled courses:")
            for idx, course in enumerate(self.current_user.enrolled_courses, 1):
                print(f"{idx}. {course.course_name} (ID: {course.course_id})")
                print(f"   Teacher: {course.teacher.username}")
            
            # 让学生选择要退的课程
            choice = input(f"\nEnter course number to drop (1-{len(self.current_user.enrolled_courses)}) or '0' to cancel: " ).strip()
            
            if choice == "0":
                print("❌ Drop operation cancelled.")
                return
            
            try:
                choice_num = int(choice)
                if 1 <= choice_num <= len(self.current_user.enrolled_courses):
                    selected_course = self.current_user.enrolled_courses[choice_num - 1]
                    
                    # 调用Student的drop_course方法
                    result = self.current_user.drop_course(selected_course)
                    
                    if result:
                        print(f"✅ Successfully dropped course '{selected_course.course_name}'!")
                        self.update_user_incrementally(self.current_user)  # 增量保存用户数据
                    else:
                        print(f"❌ Failed to drop course '{selected_course.course_name}'.")
                else:
                    print("❌ Invalid course number.")
            except ValueError:
                print("❌ Please enter a valid number.")
                
        except Exception as e:
            error_handling(e)
            print("⚠️  Course drop operation failed. Please check the system logs for more details.")

    def _handle_approve_course(self) -> None:
        """处理管理员批准课程"""
        self.create_backup_before_operation("course_approval")
        
        try:
            # 获取所有待审批的课程
            pending_courses = [course for course in Course.all_courses() if course.status == "pending"]
            
            if not pending_courses:
                print("\nThere are no pending courses to approve.")
                return
            
            # 显示待审批课程列表
            print("\n=== Pending Courses to Approve ===")
            for i, course in enumerate(pending_courses, 1):
                # 添加对teacher是否为None的检查
                teacher_name = course.teacher.username if course.teacher else "Unknown"
                print(f"{i}. Course ID: {course.course_id} | Course Name: {course.course_name} | Created by: {teacher_name}")
        
            # 选择要审批的课程
            choice = input_validation.input_choice("Enter course number to approve (1-{}): ".format(len(pending_courses)), len(pending_courses))
            if choice is None:
                return
            
            selected_course = pending_courses[choice - 1]
            
            # 显示课程详情
            print(f"\n=== Course Details ===")
            print(f"Course ID: {selected_course.course_id}")
            print(f"Course Name: {selected_course.course_name}")
            print(f"Course Description: {selected_course.description}")
            print(f"Max Students: {selected_course.max_students}")
            # 显示课程详情时添加安全检查
            print(f"Created by: {selected_course.teacher.username if selected_course.teacher else 'Unknown'}")
        
            # 管理员审批
            action = input("Enter action (approve/reject/cancel): ").lower()
        
            if action == "approve":
                # 调用管理员的approve_course方法
                if isinstance(self.current_user, Administrator):
                    self.current_user.approve_course(selected_course)
                    # 更新课程状态
                    selected_course.status = "approved"
                    # 重新保存课程数据
                    self.save_course_incrementally(selected_course)
                    print(f"\n✅ Course '{selected_course.course_name}' has been approved!")
                else:
                    print("❌ Only administrators can approve courses.")
            elif action == "reject":
                # 设置课程状态为已拒绝
                selected_course.status = "rejected"
                # 重新保存课程数据
                self.save_course_incrementally(selected_course)
                print(f"\n✅ Course '{selected_course.course_name}' has been rejected.")
            elif action == "cancel":
                print("\n✅ Operation cancelled.")
            else:
                print("\n❌ Invalid action. Please enter 'approve', 'reject', or 'cancel'.")
        except Exception as e:
            error_handling(e)
            print("⚠️ Course approval operation failed. Please check the system logs for more details.")


    def _handle_create_course(self) -> None:
        """处理教师创建课程"""
        self.create_backup_before_operation("course_creation")
        """处理教师创建课程"""
        try:
            # 输入课程信息
            print("\n=== Create New Course ===")
            course_name = input("Enter course name: ").strip()
            if not course_name:
                print("❌ Course name cannot be empty!")
                return
        
            description = input("Enter course description (optional): ").strip()
            max_students = input_positive_integer("Enter max students (default 30): ", 30)
        
            # 生成课程ID
            course_id = generate_id("COURSE_")
        
            # 创建课程实例
            course = Course(
                course_id=course_id,
                course_name=course_name,
                teacher=self.current_user,
                max_students=max_students,
                course_description=description,
                status="pending"  # 设置状态为待审批
            )
        
            # 将课程添加到教师的管理课程列表
            if isinstance(self.current_user, Teacher):
                self.current_user.manage_course(course)
        
            # 保存课程数据
            self.save_course_incrementally(course)
        
            print(f"\n✅ Course '{course_name}' (ID: {course_id}) has been created! Awaiting approval from the administrator.")
        except Exception as e:
            error_handling(e)
            print("⚠️ Course creation operation failed. Please check the system logs for more details.")
    
    def _handle_view_class_roster(self):
        """处理教师查看班级花名册功能"""
        print("\n" + "="*50)
        print("=== View Class Roster ===")
        print("="*50)
        
        try:
            # 检查教师是否有管理的课程
            if not self.current_user.managed_courses:
                print("❌ You don't have any managed courses!")
                return
        
            # 显示教师管理的课程列表
            print("Your managed courses:")
            for idx, course in enumerate(self.current_user.managed_courses, 1):
                print(f"{idx}. {course.course_name} (ID: {course.course_id})")
                print(f"   Students enrolled: {len(course.enrolled_students)}")
        
            # 让教师选择要查看的课程
            choice = input(f"\nEnter course number to view roster (1-{len(self.current_user.managed_courses)}) or '0' to cancel: ").strip()
        
            if choice == "0":
                print("❌ Operation cancelled.")
                return
        
            try:
                choice_num = int(choice)
                if 1 <= choice_num <= len(self.current_user.managed_courses):
                    selected_course = self.current_user.managed_courses[choice_num - 1]
                    # 调用Teacher的view_class_roster方法
                    self.current_user.view_class_roster(selected_course)
                else:
                    print("❌ Invalid course number.")
            except ValueError:
                print("❌ Please enter a valid number.")
            
        except Exception as e:
            error_handling(e)
            print("⚠️  View class roster operation failed. Please check the system logs for more details.")

    def _handle_grade_assignment(self):
        """处理作业评分"""
        self.create_backup_before_operation("assignment_grading")
        """处理作业评分"""
        if not isinstance(self.current_user, Teacher):
            print("❌ Only teachers can grade assignments.")
            return
            
        try:
            # 显示教师管理的课程
            managed_courses = self.current_user.managed_courses
            if not managed_courses:
                print("⚠️  You are not managing any courses.")
                return
                
            print("\nYour managed courses:")
            for i, course in enumerate(managed_courses, 1):
                print(f"{i}. {course.course_name} (ID: {course.course_id})")
                
            # 选择课程
            choice = input("Select a course to grade assignments (1-{}): ".format(len(managed_courses))).strip()
            try:
                course_index = int(choice) - 1
                if course_index < 0 or course_index >= len(managed_courses):
                    print("❌ Invalid course selection.")
                    return
                selected_course = managed_courses[course_index]
            except ValueError:
                print("❌ Invalid input. Please enter a number.")
                return
                
            # 显示课程中的作业
            if hasattr(selected_course, 'course_assignments') and selected_course.course_assignments:
                print("\nAssignments in this course:")
                for i, assignment in enumerate(selected_course.course_assignments, 1):
                    print(f"{i}. {assignment.title} (Due: {assignment.due_date})")
                    
                # 选择作业
                assignment_choice = input("Select an assignment to grade (1-{}): ".format(
                    len(selected_course.course_assignments))).strip()
                try:
                    assignment_index = int(assignment_choice) - 1
                    if assignment_index < 0 or assignment_index >= len(selected_course.course_assignments):
                        print("❌ Invalid assignment selection.")
                        return
                    selected_assignment = selected_course.course_assignments[assignment_index]  
                except ValueError:
                    print("❌ Invalid input. Please enter a number.")
                    return
            else:
                print("⚠️  No assignments found for this course.")
                # 创建一个新的作业
                create_new = input("Would you like to create a new assignment? (y/n): ").strip().lower()
                if create_new != 'y':
                    return
                    
                title = input("Enter assignment title: ").strip()
                description = input("Enter assignment description: ").strip()
                due_date_str = input("Enter due date (YYYY-MM-DD HH:MM): ").strip()

                assignment_info = {
                    "title": title,
                    "content": description,
                    "due_date": due_date_str,
                }

                selected_assignment = self.current_user.create_assignment(selected_course, assignment_info)

                if not selected_assignment:
                    print("⚠️  Failed to create assignment.")
                    return
                
                # 添加到课程
                if not hasattr(selected_course, '_course_assignments'):
                    selected_course.course_assignments = []
                selected_course.course_assignments.append(selected_assignment)
            
            # 显示提交该作业的学生
            if selected_assignment.submissions:
                print("\nStudents who submitted this assignment:")
                for i, (student_id, submission) in enumerate(selected_assignment.submissions.items(), 1):
                    # 查找学生对象获取姓名
                    student_name = "Unknown"
                    for user in User.all_users():
                        if isinstance(user, Student) and user.student_id == student_id:
                            student_name = user.username
                            break
                    status = "Graded" if submission[1] is not None else "Not Graded"
                    score_text = f" (Score: {submission[1]})" if submission[1] is not None else ""
                    print(f"{i}. {student_name} (ID: {student_id}) - {status}{score_text}")
            else:
                print("⚠️  No submissions found for this assignment.")
                # 选择学生进行评分
                print("\nStudents enrolled in this course:")
                enrolled_students = []
                for user in User.all_users():
                    if isinstance(user, Student):
                        for course in user.enrolled_courses:
                            if course.course_id == selected_course.course_id:
                                enrolled_students.append(user)
                                break
                
                if enrolled_students:
                    for i, student in enumerate(enrolled_students, 1):
                        print(f"{i}. {student.username} (ID: {student.student_id})")
                        
                    # 选择学生
                    student_choice = input("Select a student to grade (1-{}): ".format(len(enrolled_students))).strip()
                    try:
                        student_index = int(student_choice) - 1
                        if student_index < 0 or student_index >= len(enrolled_students):
                            print("❌ Invalid student selection.")
                            return
                        selected_student = enrolled_students[student_index]
                        
                        # 为该学生创建一个提交记录
                        from datetime import datetime
                        selected_assignment.submissions[selected_student.student_id] = (datetime.now(), None)
                        print(f"Created submission record for {selected_student.username}.")
                    except ValueError:
                        print("❌ Invalid input. Please enter a number.")
                        return
                else:
                    print("⚠️  No students enrolled in this course.")
                    return
            
            # 进行评分
            student_id = input("Enter student ID to grade (or select from list above): ").strip()
            if student_id.startswith("ID"):
                student_id = student_id.replace("ID:", "", 1).strip()
            if not student_id:
                print("❌ No student ID entered.")
                return
                
            # 验证学生是否提交了作业
            if student_id not in selected_assignment.submissions:
                print("❌ This student did not submit the assignment.")
                return
                
            # 获取学生姓名
            student_name = "Unknown"
            for user in User.all_users():
                if isinstance(user, Student) and user.student_id == student_id:
                    student_name = user.username
                    break
                    
            # 输入分数
            score_input = input(f"Enter score for {student_name} (0-{selected_assignment.total_points}): ").strip()
            try:
                score = float(score_input)
                # 使用GradingSystem进行评分
                if self.grading_system.grade_assignment(selected_assignment, student_id, score):
                    # 更新学生的成绩记录
                    for user in User.all_users():
                        if isinstance(user, Student) and user.student_id == student_id:
                            self._sync_grades_to_students()
                            self.save_data()  # 保存更新后的成绩
                            break
            except ValueError:
                print("❌ Invalid score. Please enter a number.")
                return
                
        except Exception as e:
            error_handling(e)
            print("⚠️  Failed to grade assignment.")

    def sync_course_data(self):
        try:
            for course in self.courses:
                if course not in Course._all_courses:
                    Course._all_courses.append(course)

            for course in Course._all_courses:
                if course not in self.courses:
                    self.courses.append(course)

            print("课程数据同步完成")
            return True
        except Exception as e:
            print(f"课程数据同步失败: {str(e)}")
            return False

    def _sync_grades_to_students(self):
        """同步评分系统中的成绩到学生对象"""
        for student in self.students:
            for course in student.enrolled_courses:
                # 计算并更新学生的课程总成绩
                total_score = self.grading_system.calculate_total_score(student.student_id, course)
                if total_score > 0:
                    student.grades[course] = total_score